package api

import (
	auto "beergo/app/check/auto/controller"
	"beergo/app/check/conf"
	"beergo/app/check/documents"
	"context"
	"github.com/beego/beego/v2/server/web"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type LbsController struct {
	auto.GeoMongoDbController
}

func init() {
	web.Router(conf.UrlPrefix + "/Geo/near",&LbsController{}, "*:LbsAction")
}

func (this *LbsController) LbsAction() {
	lat := this.GetParamFloat64("lat")
	lng := this.GetParamFloat64("lng")
	key :=this.GetParamString("key")
	src :=this.GetParamString("src")


	georep:=documents.GeoRepository{}
	qs:=georep.GetQuerySetter()
	opt:=options.Find().SetLimit(50).SetLimit(0)
	c,e:=qs.Find(context.TODO(),bson.D{
		{"loc",createNear(lng,lat)},
		{"src",src},
		{"srcData.name",bson.D{
			{"$regex",key},
		}},
	},opt)
	if e != nil {println("ERROR",e.Error())}
	data := make([]map[string]interface{},0)
	if c != nil {
		err:=c.All(context.TODO(),&data)
		if err != nil {
			print("lbs err",err.Error())
		}
	}

	println(lat)

	this.ReturnSuccess("OK",data)
}

func createNear(lat float64,lng float64) bson.D {
	return bson.D{
		{"$near",bson.D{
			{"$geometry",bson.D{
				{"type","Point"},
				{"num",10},
				{"coordinates",[]float64{lat,lng}},
			}},
		}},
	}
}
